package solutions.leetcode.normal;

import solutions.lib.BaseSolution;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * @author lizhidong
 * <a href="https://leetcode-cn.com/problems/peeking-iterator/">284. 窥探迭代器</a>
 */
public class Solution284 extends BaseSolution {

    static class PeekingIterator implements Iterator<Integer> {
        final Iterator<Integer> iterator;
        Integer nextVal;

        public PeekingIterator(Iterator<Integer> iterator) {
            // initialize any member here.
            this.iterator = iterator;
        }

        // Returns the next element in the iteration without advancing the iterator.
        public Integer peek() {
            if (nextVal == null) {
                nextVal = iterator.next();
            }
            return nextVal;
        }

        // hasNext() and next() should behave the same as in the Iterator interface.
        // Override them if needed.
        @Override
        public Integer next() {
            Integer next;
            if (nextVal != null) {
                next = nextVal;
                nextVal = null;
            } else {
                next = iterator.next();
            }
            return next;
        }

        @Override
        public boolean hasNext() {
            return nextVal != null || iterator.hasNext();
        }
    }

    public static void main(String[] args) {
        Solution284 solution = new Solution284();
    }
}